// index.js
// 获取应用实例
const app = getApp()

const api = require('./../../api/api')
import Toast from "./../../miniprogram/miniprogram_npm/@vant/weapp/toast/toast"
import {
  checkValidResData
} from "./../../utils/checknull";


Page({
  data: {
    first_login: true,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    showOverLay: false, // 遮罩层
  },

  /*
   * 发送用户信息并获取用户的openid
   * 200 represent success
   * 400 represent error
   */
  PostUserInfo: async () => {
    let sendData = {
      'nickName': wx.getStorageSync('nickName'),
      'avatarUrl': wx.getStorageSync('avatarUrl'),
      'gender': wx.getStorageSync('gender'),
      'openid': wx.getStorageSync('openid'),
    }
    console.log(sendData);

    try {
      if (checkValidResData(sendData.openid) == false)
        throw 'empty openid'
      let res = await api.post("/user/login", sendData);
      console.log(res)
      if (res.statusCode != 200) {
        throw res;
      }
      if (res.data.rescode != 200) {
        throw res.data
      } else {
        // let openid = res.data.openid;
        // // 将openid保存到缓存
        // wx.setStorageSync('openid', openid);
        // console.log('缓存中的openid', wx.getStorageSync('openid'));
        return 200;
      }
    } catch (error) {
      console.log("error", error)
      return 400;
    }
  },
  GetUserInfo:async ()=> {
    try {
      let res = await api.post("/user/checkreg", {
        userCode: wx.getStorageSync('userCode')
      });
      console.log(res);
      if (res.statusCode != 200) {
        // network error
        Toast('网络错误');
      } else {
        if (checkValidResData(res.data.openid))
          wx.setStorageSync('openid', res.data.openid);
        else
          throw '未能成功获取用户标识';

        if (res.data.rescode != 200)
          throw '错误';

        if (checkValidResData(res.data.nickName))
          wx.setStorageSync('nickName', res.data.nickName);
        else
          throw '昵称为空';

        if (checkValidResData(res.data.avatarUrl))
          wx.setStorageSync('avatarUrl', res.data.avatarUrl);
        else
          throw '头像为空';

        if (checkValidResData(res.data.gender))
          wx.setStorageSync('gender', res.data.gender);
        else
          throw '性别为空';
        Toast('登录成功');
        wx.switchTab({
          url: "/pages/tarbarpages/home/index/index"
        })
      }
    } catch (ex) {
      console.log(ex);
      // Toast(`${ex}`);
      return 400;
    } 
    return 200;
  },
  /**
   * event handle of btn of recoginze
   */
  bindGetUserInfo: async function (e) {
    let rescode;
    this.setData({
      showOverLay: true
    })
    if(this.data.first_login == false){
      // 此时是有的
      rescode = await this.GetUserInfo();
    }
    else{
      wx.setStorageSync('nickName', e.detail.userInfo.nickName);
      wx.setStorageSync('avatarUrl', e.detail.userInfo.avatarUrl);
      wx.setStorageSync('gender', e.detail.userInfo.gender);
      // console.log(wx.getStorageSync('nickName'));
      // console.log(wx.getStorageSync('avatarUrl'));
      // 此时则可以将所有信息一起送到服务器
      rescode = await this.PostUserInfo();
    }
    this.setData({
      showOverLay: false
    })

    if (rescode == 200) {
      Toast('成功');
      wx.switchTab({
        url: "/pages/tarbarpages/home/index/index"
      });
    } else {
      Toast('错误');
    }
  },

  /**
   * 使用小程序时先进行判断是否以前使用过
   */
  onLoad: async function (options) {
    console.log(options);
    let appres = await app.getCode();
    console.log(appres);
    if (appres.code == null || appres.code == undefined || appres.code == "") {
      Toast('未能获取用户码');
      return;
    }
    wx.setStorageSync('userCode', appres.code);
    // 退出登录时候来的不需要跳转
    if (options.exit == 'true') {
      this.setData({
        first_login: false
      })
      return;
    }

    this.setData({
      showOverLay: true
    })

    try {
      let res = await api.post("/user/checkreg", {
        userCode: appres.code
      });
      console.log(res);
      if (res.statusCode != 200) {
        // network error
        Toast('网络错误');
      } else {
        if (checkValidResData(res.data.openid))
          wx.setStorageSync('openid', res.data.openid);
        else
          throw '未能成功获取用户标识';

        if (res.data.rescode != 200)
          return;

        if (checkValidResData(res.data.nickName))
          wx.setStorageSync('nickName', res.data.nickName);
        else
          throw '昵称为空';

        if (checkValidResData(res.data.avatarUrl))
          wx.setStorageSync('avatarUrl', res.data.avatarUrl);
        else
          throw '头像为空';

        if (checkValidResData(res.data.gender))
          wx.setStorageSync('gender', res.data.gender);
        else
          throw '性别为空';
        Toast('登录成功');
        wx.switchTab({
          url: "/pages/tarbarpages/home/index/index"
        })
      }
    } catch (ex) {
      console.log(ex);
      Toast(`${ex}`);
    } finally {
      this.setData({
        showOverLay: false
      })
    }
  },
})